package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.Taskinfo;
import com.heima.model.schedule.TaskinfoLogs;
import com.heima.model.schedule.dto.Task;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;


import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static com.heima.common.constants.ScheduleConstants.*;


@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private  CacheService cacheService;
    @Override
    public Long addTask(Task task) {
        //1.添加任务到数据库
       boolean success=addTaskTob(task);
        //2.天添加任务到redis
        if (success) {
            redisAdd(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     * @param taskId        任务id
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        //删除数据库任务相关信息
        Task c= RemoveAndUpdate(taskId);
        //删除redis里面的任务信息
        if (c!=null) {
           RemoveRedis(c);
        }

        return false;
    }

    /**
     * 根据优先级和类别组成redis的key取消费redis里面缓存的任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
       Task task=null;
       String key=type+"_"+priority;
        try {
            String lRightPop = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (!StringUtils.isEmpty(lRightPop))
                task = JSON.parseObject(lRightPop,Task.class);
                //redis里面的任务消费后删除和更改数据库数据
                 RemoveAndUpdate(task.getTaskId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return task;
    }

    /**
     * 定时刷新
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        //获取所有未来数据的集合
        Set<String> taskKeys = cacheService.scan(FUTURE + "*");
        if (StringUtils.isNotEmpty(token)) {
            log.info("刷新未来任务数据开始");
            for (String taskKey:taskKeys)
            {
                String topiKey = FUTURE+ taskKey.split(FUTURE)[1];
                Set<String> taskSet = cacheService.zRangeByScore(topiKey, 0, System.currentTimeMillis());
                if (taskSet.size()>0)
                {
                    cacheService.refreshWithPipeline(taskKey,topiKey,taskSet);
                    log.info("刷新成功");
                }
            }
        }
    }

    /**
     * 数据库数据定期同步redis
     */

    @Scheduled(cron = "0 */5 * * * ?")
    @Override
    //@PostConstruct这个注解是在spring容器初始化的时候执行，没有任何方法调用他也会执行，初始化数据
    @PostConstruct
    public void dbPushRedis() {
        //清理缓存中的数据
        clearCache();
        //查询小于五分钟的任务
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));
        //更新缓存中的数据
        if (taskinfos!=null&&taskinfos.size()>0)
        {
            taskinfos.forEach(taskinfo -> {
                Task task=new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTask(task);

            });
        }

    }

    private void clearCache() {
        Set<String> topicKeys = cacheService.scan(TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);

    }

    private void RemoveRedis(Task task) {
        String key=task.getTaskType()+"_"+task.getPriority();
        //判断任务的时间
        if ( task.getExecuteTime()<=System.currentTimeMillis())
        {
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));

        }
        else if (task.getExecuteTime()>System.currentTimeMillis())
        {
            cacheService.zRemove(FUTURE+key,0,JSON.toJSONString(task));
        }
    }

    //任务取消删除（修改）数据库相关信息
    private Task RemoveAndUpdate(long taskId) {
        Task task = null;
        try {
            task = new Task();
            Taskinfo taskinfo = taskinfoMapper.selectById(taskId);
            BeanUtils.copyProperties(taskinfo,task);
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(CANCELLED);
            taskinfoLogsMapper.updateById(taskinfoLogs);


            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return task;

    }

    /**
     * 任务放进redis
     * @param task
     */
    private void redisAdd(Task task) {

        String key=task.getTaskType()+"_"+task.getPriority();
        //获取五分钟后的毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        //五秒后的毫秒值
        long timeInMillis = calendar.getTimeInMillis();
        //2.1 如果任务执行的时间小于当前时间。存在list里面
        if (task.getExecuteTime() <= System.currentTimeMillis())
        {
                cacheService.lLeftPush(ScheduleConstants.TOPIC+key,JSON.toJSONString(task));
        }

        //2.2 如果任务执行时间大于当前时间，参在zset里面
        else  if (timeInMillis>=System.currentTimeMillis())
        {
                cacheService.zAdd(FUTURE+key,JSON.toJSONString(task)
                ,task.getExecuteTime());
        }
    }
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    private boolean addTaskTob(Task task) {
        boolean flag = false;
        try {
            //保存任务表
            Taskinfo taskinfo=new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //保存任务日志表
            TaskinfoLogs taskinfoLogs=new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(EXECUTED);
            taskinfoLogs.setStatus(SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag=true;
        } catch (BeansException e) {

            throw new RuntimeException(e);
        }
        return flag;
    }
}
